<template>
  <el-upload
    v-loading="loading"
    class="uploader"
    :disabled="disabled"
    :accept="props.accept"
    :before-upload="beforeUpload"
    :http-request="httpRequest"
    :show-file-list="false"
  >
    <slot name="tip"></slot>
    <template #trigger>
      <el-button plain :disabled="disabled">
        <el-icon>
          <Upload />
        </el-icon>
        <span>上传文件</span>
      </el-button>
    </template>
    <slot></slot>
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { genFileId } from 'element-plus';
import COS from 'cos-js-sdk-v5';
import { fileService } from '@/api/file';
import moment from 'moment';
import type { UploadInstance, UploadProps, UploadUserFile, UploadRawFile } from 'element-plus';
import { commonService } from '@/api/common';
const props = defineProps({
  accept: {
    type: String,
    default: '.pdf,.doc,.docx,.jpg,.png',
  },
  size: {
    type: Number,
    default: 10,
  },
  uploadUrl: {
    typeof: String,
    default: '/robot-api/admin/file/upload',
  },
  fileNames: {
    typeof: String,
    default: 'files',
  },
  listType: {
    typeof: String,
    default: 'picture-list',
  },
  files: {
    type: Array,
    default: [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const upload = ref<UploadInstance>();
const loading = ref(false);
const beforeUpload = (file) => {
  const isSizeLimit = file.size / 1024 / 1024 < props.size;
  const arr = file.name.split('.');
  const ext = arr[arr.length - 1];
  if (props.accept != '*' && props.accept.indexOf(ext) == -1) {
    ElMessage({
      message: `只能上传${props.accept}格式文件!`,
      type: 'error',
    });
    return false;
  }
  if (!isSizeLimit) {
    ElMessage({
      message: `上传文件大小不能超过${props.size}MB!`,
      type: 'error',
    });
  } else {
    if (import.meta.env.VITE_USER_NODE_ENV == 'stagingcq' || import.meta.env.VITE_USER_NODE_ENV === 'development') {
      fileCOSChange(file);
    } else fileChange(file);
  }
  return isSizeLimit;
};
const fileChange = (file) => {
  const formData = new FormData();
  formData.append('file', file);
  //formData.append('filename', file.name)
  const arr = file.name.split('.');
  const accept = arr[arr.length - 1];
  const fileName = moment().format('YYYYMMDD') + Math.round((Math.random() + 0.1) * 100000) + '.' + accept;
  const url = `${import.meta.env.VITE_CONFIG_FILE}/put?filechannel=webchat&filetype=${accept}&filename=${fileName}`;
  fetch(url, {
    method: 'POST',
    body: formData,
  })
    .then((res) => {
      if (res.status == 200) {
        res.text().then((text) => {
          let file = {
            name: fileName,
            url: `${import.meta.env.VITE_CONFIG_FILE}/get?filename=${text}`,
          };
          const listType = props.listType;
          if (listType === 'picture' || listType === 'avatar') {
            filePictureChange(file);
          } else if (listType === 'text') {
            fileTextChange(file);
          } else if (listType === 'picture-list') {
            fileTextChange(file);
          }
        });
      } else {
        ElMessage({
          message: '上传失败',
          type: 'error',
        });
      }
    })
    .then((restext) => {
      //console.log("text====",restext)
    });
  /* fileService.upLoad(formData, url).then((res) => { }) */
};
const httpRequest: any = () => {};
const cos = ref(null);
const bucket = ref(null);
const endpoint = ref(null);
const accessKeyId = ref(null);
const secretAccessKey = ref(null);
const fileSystemCloudProvider = ref(null);
const fileList = ref([]);
fileList.value = [...props.files];
watch(
  () => props.files,
  (val) => {
    fileList.value = [...val];
  },
  { deep: true },
);
const sessionToken = ref(null);
const fileUrl = ref('');
const emit = defineEmits(['update:files']);

const fileCOSChange = (file) => {
  // const files = file.target.files[0]
  const files = file;
  let ContentType = 'text/plain';
  // const name = fileName.value
  const arr = files.name.split('.');
  const accept = arr[arr.length - 1];
  const fileName = moment().format('YYYYMMDD') + Math.round((Math.random() + 0.1) * 100000) + '.' + accept;
  let params = {
    Bucket: bucket.value,
    Key: props.fileNames + '/' + fileName,
    Body: files,
    Region: 'ap-chongqing',
    ACL: 'public-read', // 初始化acl权限，默认为private，"private"|"public-read"|"public-read-write"
    ContentType: ContentType, // 设置contentType, 默认是application/octet-stream
  };
  cos.value.putObject(params, (err, data) => {
    // console.log('erro====', err)
    loading.value = false;
    console.log(data);

    if (err) {
      console.log(err);
    } else {
      let file = {
        // name: files.name,
        name: fileName,
        url: `https://${data.Location}`,
      };
      const listType = props.listType;
      if (listType === 'picture' || listType === 'avatar') {
        filePictureChange(file);
      } else if (listType === 'text') {
        fileTextChange(file);
      } else if (listType === 'picture-list') {
        fileTextChange(file);
      }
    }
  });
};
const fileTextChange = (file) => {
  fileList.value.push(file);
  console.log(fileList.value);
  emit('update:files', fileList.value);
};
const filePictureChange = (file) => {
  fileUrl.value = file.url;
  emit('update:files', fileList.value);
};
const getKey = () => {
  commonService.uploadFiles(props.uploadUrl).then((res) => {
    bucket.value = res.data.bucket;
    endpoint.value = res.data.endpoint;
    accessKeyId.value = res.data.accessKeyId;
    secretAccessKey.value = res.data.secretAccessKey;
    sessionToken.value = res.data.sessionToken;
    fileSystemCloudProvider.value = res.data.fileSystemCloudProvider;
    if (fileSystemCloudProvider.value == 3) {
      cos.value = new COS({
        getAuthorization(option, callback) {
          callback({
            TmpSecretId: res.data.accessKeyId,
            TmpSecretKey: res.data.secretAccessKey,
            SecurityToken: res.data.sessionToken,
            ExpiredTime: res.data.expireEndTime,
            StartTime: res.data.startTime,
          });
        },
      });
    }
  });
};
onMounted(() => {
  if (import.meta.env.VITE_USER_NODE_ENV == 'stagingcq' || import.meta.env.VITE_USER_NODE_ENV === 'development') {
    getKey();
  }
  //
});
</script>
<style lang="scss" scoped>
.uploader {
  width: 100%;
}
</style>
